const wxpay = require('../../utils/pay.js')
const app = getApp()
const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')

Page({
  data: {
    //0:待付款 1:已付款 2:已发货 3:已收货 4:退款中 5:订单关闭
    statusType: [ 
      {id: 8,name: "全部"},
      {id: 0,name: "待付款"},
      {id: 1,name: "待发货"},
      {id: 3,name: "已完成"},
      {id: 4,name: "退款列表"},
    ],
    hasRefund: false,
    currentType: 8,
    tabClass: ["", "", "", "", ""],
    showModal1: false,
    modalType: 'changeAmt',
    currentId: 0,
    currentOrderData: null,
    changeAmtNum: 0,
    initAmt: 0,
    refundAmt: 0,
    refundRes: '',
    curRefundNo: 0,
    changeAmtText:'',
    curShop: wx.getStorageSync('_curShop')
  },
  toDeatil(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/order-details/index?id=" + id
    })

  },
  changeConfirm(){
    //确认修改价格
    const {changeAmtNum, changeAmtText, currentId , modalType, refundAmt} = this.data
    const { merShopInfos } = wx.getStorageSync('curUserInfo')
    if(!changeAmtNum && modalType === 'changeAmt'){
      wx.showToast({
        title: '请输入新的价格',
        icon: 'none',
        duration: 2000
      })
    }else if(!refundAmt && modalType === 'toRefund'){
      wx.showToast({
        title: '请输入退款价格',
        icon: 'none',
        duration: 2000
      })
    }else{
      if(modalType === 'toRefund'){
        this.confirmRefund()
      }else{
      const postData = {
        "actOrderAmt": changeAmtNum,
        "merMemo": changeAmtText,
        "orderNo": currentId,
        "shopNo": wx.getStorageSync('_curShop').shopNo
      }
      WXAPI.updateMerOrder(postData).then((res) => {
        if(res.retCode === '200'){
          this.setData({ showModal1: false })
          wx.showToast({
            title: '修改价格成功',
            icon: 'success',
            duration: 2000
          })
          this.onShow()
        }else{
          wx.showToast({
            title: res.retMsg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }}
  },
  changeCancel(){
    //取消修改价格
    this.setData({ showModal1: false })
  },
  changeAmt(e){
    //修改的价格
    if(this.data.modalType === 'toRefund'){
      this.setData({
        refundAmt: e.detail.value
      })
    }else{
      this.setData({
        changeAmtNum: e.detail.value
      })
    }
  },
  changeAmtRes(e){
    //改价原因
    if(this.data.modalType === 'toRefund'){
      this.setData({
        refundRes: e.detail.value
      })
    }else{
      this.setData({
        changeAmtText: e.detail.value
      })
    }
  },
  toChangeAmt: function(e) {
    //修改价格
    const {id, order} = e.currentTarget.dataset
    this.setData({ showModal1: true , modalType: 'changeAmt',currentOrderData: order})
    this.data.currentId = id
    this.data.currentOrderData = order
  },
  getRefundList(){
    const { merShopInfos } = wx.getStorageSync('curUserInfo')
    const postData = {
      pageNum: 1,
      pageSize: 1000,
      refundStatus: '',
      shopNo:wx.getStorageSync('_curShop').shopNo
    }
    const that = this
    WXAPI.findRefundList(postData).then((res) => {
      if(res.retCode === '200'){
        that.setData({
          orderList: res.data.list
        });
      }else{
        that.setData({
          orderList: []
        });
      }
    })
  },
  statusTap: function(e) {
    const curType = e.currentTarget.dataset.index;
    this.data.currentType = curType
    this.setData({
      currentType: curType
    });
    this.onShow();
  },
  cancelOrderTap: function(e) {
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确定要取消该订单吗？',
      content: '',
      success: function(res) {
        if (res.confirm) {
          WXAPI.orderClose(orderId).then(function(res) {
            if (res.retCode === '200') {
              that.onShow();
            }
          })
        }
      }
    })
  },
  confirmRefund(){
    const {refundRes, refundAmt, curRefundNo} = this.data;
    const postData = {
      actRefundAmt: refundAmt + '',
      "auditActionEnum": "PASS",
      "auditDesc": refundRes,
      refundOrderNo: curRefundNo
    }
    const _this = this
    // wx.showModal({
    //   title: '退款',
    //   content: `将要退款${refundAmt}元；买家留言：${refundReason}`,
    //   showCancel: false,
    //   confirmText: "确认退款",
    //   cancelText: "取消",
    //   success(res){
    //     if (res.confirm) {
          WXAPI.refundAudit(postData).then((res) => {
            this.setData({ showModal1: false })
            if(res.retCode === '200'){
              wx.showToast({
                title: '审核成功',
                icon: 'success',
                duration: 2000
              })
              _this.onShow()
            }else{
              wx.showToast({
                title: res.retMsg,
                icon: 'none',
                duration: 2000
              })
              _this.onShow()
            }
          // })
        // } 
      // }
    })
  },
  toRefund(e){
    //退款审核amount
    const id = e.currentTarget.dataset.id
    const { actRefundAmt } = e.currentTarget.dataset.amount
    const {refundOrderNo} = e.currentTarget.dataset.amount;
    this.setData({curRefundNo: refundOrderNo,initAmt:actRefundAmt,refundAmt:actRefundAmt })
    this.data.currentId = id
    this.confirmRefund()
    // const {refundReason, refundAmt, actRefundAmt, refundOrderNo} = e.currentTarget.dataset.amount;
    // const postData = {
    //   actRefundAmt: actRefundAmt + '',
    //   "auditActionEnum": "PASS",
    //   "auditDesc": "",
    //   refundOrderNo
    // }
    // const _this = this
    // wx.showModal({
    //   title: '退款',
    //   content: `将要退款${refundAmt}元；买家留言：${refundReason}`,
    //   showCancel: false,
    //   confirmText: "确认退款",
    //   cancelText: "取消",
    //   success(res){
    //     if (res.confirm) {
    //       WXAPI.refundAudit(postData).then((res) => {
    //         if(res.retCode === '200'){
    //           wx.showToast({
    //             title: '审核成功',
    //             icon: 'success',
    //             duration: 2000
    //           })
    //           _this.onShow()
    //         }else{
    //           wx.showToast({
    //             title: res.retMsg,
    //             icon: 'none',
    //             duration: 2000
    //           })
    //           _this.onShow()
    //         }
    //       })
    //     } 
    //   }
    // })
  },
  toDispatch (e) {
    //  确认发货
    const orderId = e.currentTarget.dataset.id;
    const { merShopInfos } = wx.getStorageSync('curUserInfo')
    const postData = {
      orderNo: orderId,
      shopNo:wx.getStorageSync('_curShop').shopNo
    }
    const _this = this
    WXAPI.confirmSend(postData).then((res) => {
      if(res.retCode === '200'){
        wx.showToast({
          title: '发货成功',
          icon: 'success',
          duration: 2000
        })
        _this.onShow()
      }else{
        wx.showToast({
          title: res.retMsg,
          icon: 'none',
          duration: 2000
        })
        _this.onShow()
      }
    })
  },
  toPayTap: function(e) {
    // 防止连续点击--开始
    if (this.data.payButtonClicked) {
      wx.showToast({
        title: '休息一下~',
        icon: 'none'
      })
      return
    }
    this.data.payButtonClicked = true
    setTimeout(() => {
      this.data.payButtonClicked = false
    }, 3000)  // 可自行修改时间间隔（目前是3秒内只能点击一次支付按钮）
    // 防止连续点击--结束
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    let money = e.currentTarget.dataset.money;
    const needScore = e.currentTarget.dataset.score;
    console.log("pay data orderId=", orderId)
    const postData = {
      orderNo: orderId
    }
    WXAPI.userAmount(postData).then(function(res) {
      console.log('res--0-',res)
      if (res.retCode === '200') {
        // 增加提示框
        if (res.data.score < needScore) {
          wx.showToast({
            title: '您的积分不足，无法支付',
            icon: 'none'
          })
          return;
        }
        let _msg = '订单金额: ' + money +' 元'
        // if (res.data.balance > 0) {
        //   _msg += ',可用余额为 ' + res.data.balance +' 元'
        //   if (money - res.data.balance > 0) {
        //     _msg += ',仍需微信支付 ' + (money - res.data.balance) + ' 元'
        //   }          
        // }
        // if (needScore > 0) {
        //   _msg += ',并扣除 ' + money + ' 积分'
        // }
        // money = money - res.data.balance

        const payData = res.data
        wx.showModal({
          title: '请确认支付',
          content: _msg,
          confirmText: "确认支付",
          cancelText: "取消支付",
          success: function (res) {
            console.log(res);
            if (res.confirm) {
              // 发起支付
              // const temp = {"timeStamp":"1573994781","package":"prepay_id=wx172046215593305abef413dc1347082600","appId":"wxa5b625b63b55a186","sign":"922430F1D1E0BEE96FDA538947439D55","signType":"MD5","nonceStr":"2yqds571jg5d8ic4xmu7rbyi32b2g6y3"}

      wx.requestPayment({
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: 'MD5',
        paySign: payData.sign,
        fail: function (aaa) {
          wx.showToast({
            title: '支付失败:' + aaa
          })
        },
        success: function () {
          // 保存 formid
          WXAPI.addTempleMsgFormid(wx.getStorageSync('token'), 'pay', res.data.prepayId)
          // 提示支付成功
          wx.showToast({
            title: '支付成功'
          })
          that.onShow();
          // wx.redirectTo({
          //   url: redirectUrl
          // });
        }
      })
            } else {
              console.log('用户点击取消支付')
            }
          }
        });
      } else {
        wx.showModal({
          title: '错误',
          content: '无法获取用户资金信息',
          showCancel: false
        })
      }
    })
  },
  _toPayTap: function (orderId, money){
    const _this = this
    if (money <= 0) {
      // 直接使用余额支付
      WXAPI.orderPay(wx.getStorageSync('token'), orderId).then(function (res) {
        _this.onShow();
      })
    } else {
      wxpay.wxpay('order', money, orderId, "/pages/order-list/index");
    }
  },
  onLoad: function(options) {
    if (options && options.type) {
      if (options.type == 99) {
        this.setData({
          hasRefund: true,
          currentType: options.type
        });
      } else {
        this.setData({
          hasRefund: false,
          currentType: options.type
        });
      }      
    }
    
  },
  onReady: function() {
    // 生命周期函数--监听页面初次渲染完成

  },
  getOrderStatistics: function() {
    var that = this;
    WXAPI.orderStatistics(wx.getStorageSync('token')).then(function(res) {
      if (res.code == 0) {
        var tabClass = that.data.tabClass;
        if (res.data.count_id_no_pay > 0) {
          tabClass[0] = "red-dot"
        } else {
          tabClass[0] = ""
        }
        if (res.data.count_id_no_transfer > 0) {
          tabClass[1] = "red-dot"
        } else {
          tabClass[1] = ""
        }
        if (res.data.count_id_no_confirm > 0) {
          tabClass[2] = "red-dot"
        } else {
          tabClass[2] = ""
        }
        if (res.data.count_id_no_reputation > 0) {
          tabClass[3] = "red-dot"
        } else {
          tabClass[3] = ""
        }
        if (res.data.count_id_success > 0) {
          //tabClass[4] = "red-dot"
        } else {
          //tabClass[4] = ""
        }

        that.setData({
          tabClass: tabClass,
        });
      }
    })
  },
  onShow: function() {
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        this.doneShow();
        this.setData({
          curShop: wx.getStorageSync('_curShop')
        })
        this.data.curShop = wx.getStorageSync('_curShop')
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: "/pages/my/index"
              })
            } else {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },
  doneShow: function() {
    // 获取订单列表
    var that = this;
    const { userNo, merShopInfos } = wx.getStorageSync('curUserInfo')
    var postData = {
      // token: wx.getStorageSync('token')
      // userNo,
      shopNo: wx.getStorageSync('_curShop').shopNo
    };
    // postData.hasRefund = that.data.hasRefund;
    if (!postData.hasRefund) {
      postData.orderStatus = that.data.currentType + '';
      postData.pageNum = '1'
      postData.pageSize = 100 + ''
      // postData.userNo = wx.getStorageSync('token')
    }
    // this.getOrderStatistics();
    if(that.data.currentType === 4){
        this.getRefundList()
    }else if(that.data.currentType === 8){
      const postData = {
        pageNum: '1',
        pageSize: '100',
        // userNo,
        shopNo: wx.getStorageSync('_curShop').shopNo
      }
      WXAPI.findAllOrder(postData).then(function(res) {
        if (res.retCode == "200") {
          that.setData({
            orderList: res.data.list,
           // logisticsMap: res.data.logisticsMap,
           // goodsMap: res.data.goodsMap
          });
        } else {
          that.setData({
            orderList: null,
            logisticsMap: {},
            goodsMap: {}
          });
        }
      })
    }else{
      WXAPI.shopOrderList(postData).then(function(res) {
        if (res.retCode == "200") {
          that.setData({
            orderList: res.data.list,
           // logisticsMap: res.data.logisticsMap,
           // goodsMap: res.data.goodsMap
          });
        } else {
          that.setData({
            orderList: null,
            logisticsMap: {},
            goodsMap: {}
          });
        }
      })
    }
    
  },
  onHide: function() {
    // 生命周期函数--监听页面隐藏

  },
  onUnload: function() {
    // 生命周期函数--监听页面卸载

  },
  onPullDownRefresh: function() {
    // 页面相关事件处理函数--监听用户下拉动作

  },
  onReachBottom: function() {
    // 页面上拉触底事件的处理函数

  }
})